#!/usr/bin/env python3
import os
import re
import record_system_info
from pathlib import Path

def replace_line_in_file(line_number, new_content, file_append):

    file = open("./stat_vdbench.max_" + file_append, 'r')

    lines = file.readlines()

    file.close()

    lines[line_number] = new_content


    file = open("./stat_vdbench.max_" + file_append, 'w')

    file.writelines(lines)

    file.close()


def save_max(vdbench_command, delay, max_avg, max_avg_info, max_std, max_std_info, max_max, max_max_info):

    data_max_get = open("./stat_vdbench_max_history_" + vdbench_command, 'w+')
    line = -1
    item_avg = "avg_2-" + delay
    item_std = "std_2-" + delay
    item_max = "max_2-" + delay
    for _l in data_max_get.readlines():
        _ll = _l.strip()
        line += 1
        # skip null lines
        if not _ll:
            continue

        # skip comment lines
        if _ll.find("#") == 0:
            continue
        
        #item
        tmpidx = _ll.find("item:")
        if tmpidx == -1:
            continue
        max_item = _ll[tmpidx + 5: ].strip()
        if max_item != item_avg and max_item != item_std and max_item != item_max:
            continue

        #sys value
        tmpidx = _ll.find("value:")
        if tmpidx == -1:
            continue
        tmp_value = _ll[tmpidx + 6:].strip();
        #if int(tmp_value) != sys_value:
        #    continue

        #command value
        tmpidx = _ll.find("vdbench")
        if tmpidx == -1:
            continue
        eidx = _ll.find("paremater:")
        if eidx == -1:
            continue
        tmp_command = _ll[tmpidx: eidx - 1].strip()
        if tmp_command != vdbench_command:
            continue

        tmpidx = _ll.find("command:")
        if tmpidx == -1:
            continue
        qpsidx = _ll.find("qps:")
        if qpsidx == -1:
            continue
        old_max = _ll[qpsidx + 4: tmpidx - 1].strip()
        if max_item == item_avg:
            score = max_avg
            info = max_avg_info
        if  max_item == item_std :
            score = max_std
            info = max_std_info
        if  max_item != item_max :
            score = max_max
            info = max_max_info
        if float(old_max) >= score:
            continue

        new_content = "result qps:" + str(score) + info + "\n"
        data_max_get.close()
        replace_line_in_file(line, new_content, vdbench_command)
        data_max_get = open("./stat_vdbench_max_history_" + vdbench_command, 'w+')

    data_max_get.close()

    data_max = open("./stat_vdbench_max_history_" + vdbench_command, 'a')
    new_content = "\nresult qps:" + str(max_avg) + max_avg_info + "\n"
    data_max.write(new_content)
    new_content = "\nresult qps:" + str(max_std) + max_std_info + "\n"
    data_max.write(new_content)
    new_content = "\nresult qps:" + str(max_max) + max_max_info + "\n"
    data_max.write(new_content)
    data_max.close()
 
    return

def stat_file(_f, delay):
    sys_path = ""
    sys_value = ""
    max_avg = 0
    max_std = 0
    max_max = 0
    max_std_info = ""
    max_max_info = ""
    max_avg_info = ""
    for root, dirs, files in os.walk("./", topdown=True):
        if root != "./":
            continue
        for name in files:
            fname = os.path.join(root, name)
            if name.endswith(".swp"):
                continue
            if name.endswith(".py.swo"):
                continue
            if name.find("max") == -1:
                continue
            with open(fname, 'r') as _fd:
                for _l in _fd.readlines():
                    _ll = _l.strip()

                    # skip null lines
                    if not _ll:
                        continue
                    # skip comment lines
                    if _ll.find("#") == 0:
                        continue

                    # skip other files
                    if _ll.find(_f) == 0:
                        continue
                    #create files

                    tmpidx = name.find("proc_")
                    if tmpidx == -1:
                        continue

                    filename = name[tmpidx : ]

                    tmpidx = _ll.find("command:")
                    if tmpidx == -1:
                        continue
                    qpsidx = _ll.find("qps:")
                    if qpsidx == -1:
                        continue
                    key = _ll[qpsidx + 4: tmpidx - 1].strip()
                    val = float(key)

                    result_stat ="avg_2-" + delay
                    tmpidx = _ll.find(result_stat)
                    avg = tmpidx
                    std = -1
                    max_2 = -1
                    if (tmpidx == -1):
                        result_stat ="std_2-" + delay
                        tmpidx = _ll.find(result_stat)
                        std = tmpidx
                        if (tmpidx == -1):
                            result_stat ="max_2-" + delay
                            tmpidx = _ll.find(result_stat)
                            max_2 = tmpidx
                    if tmpidx == -1:
                        continue
                    if max_2 != -1:
                        if val > max_max :
                            max_max = val
                            max_max_info = _ll
                        continue

                    if std != -1:
                        if val > max_std :
                            max_std = val
                            max_std_info = _ll
                        continue
                    if avg != -1:
                        if val > max_avg :
                            max_avg = val
                            max_avg_info = _ll
    save_max(_f, delay, max_avg, max_avg_info, max_std, max_std_info, max_max, max_max_info)


def do_the_stat_history(delay):

    stat_file("vdbench_random_read", delay)

